import React from "react";
import './index.module.scss';
import { withRouter } from 'react-router-dom';
// import store2 from './../Common/store';

import * as Cesium from "cesium";
import 'cesium/Source/Widgets/widgets.css'
import CryptoJS from "crypto-js";
// import { getProviderViewModels } from "./provider.js";

// 引入ECharts主模块 
import * as echarts from "echarts/lib/echarts";
import { ToolboxComponent } from 'echarts/components';
echarts.use([ToolboxComponent]);
import { PieChart } from 'echarts/charts';
echarts.use([PieChart]);
import { GridComponent } from 'echarts/components';
echarts.use([GridComponent]);
// 引入折线图需要的模块 
import 'echarts/lib/component/grid';
import "echarts/lib/chart/line";
import "echarts/lib/component/title";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/legend";
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/markPoint';

class ImageryThemeGL {
  /**
   *
   * @param {{
   *  name: string
   *  bgColor?: Cesium.Color
   *  alpha?: number
   *  invert?: boolean
   * }} options
   */
  constructor(options) {
    this.params = options;

    this.shaders = {
      bgFS: `
uniform sampler2D u_map;
uniform vec4 u_bgColor;
varying vec2 v_textureCoordinates;
void main(){
    vec2 uv = v_textureCoordinates;
    vec4 bgColor = u_bgColor;
    vec4 color = texture2D( u_map , uv );
    if( color.a > 0. ){
        gl_FragColor = bgColor;
    }
}
      `,
      mainFS: `
uniform sampler2D u_map;
uniform bool u_invert;
uniform float u_alpha;

varying vec2 v_textureCoordinates;
void main(){
    vec2 uv = v_textureCoordinates;
    vec4 color = texture2D( u_map , uv );
    //计算灰度
    float grayVal =( color.r + color.g + color.b ) / 3.;
    //灰度反转
    if(u_invert){
        grayVal = 1. - grayVal;
    }
    //应用前景透明度，以便和背景混合
    float alpha = color.a * u_alpha;
    gl_FragColor=vec4( vec3( grayVal ) , alpha );
}
      `,//`这里贴处理瓦片图像的shader代码`,
      uniformMap: {
        u_invert() {
          return true;
        },
        u_alpha() {
          return 0.5;
        },
        u_bgColor() {
          return Cesium.Color.fromCssColorString("#2e4e7e").withAlpha(0.6);
        },
      },
    };
  }

  /**
   *
   * @param {Cesium.Context} context
   * @param {Cesium.Texture} texture
   * @returns {Cesium.Texture}
   */
  processTexture(context, texture) {
    const { params, shaders } = this;
    const sampler = texture.sampler;
    const {
      Texture,
      PixelFormat,
      PixelDatatype,
      WebGLConstants,
      Framebuffer,
      RenderState,
      BlendingState,
      Color,
      defined,
    } = Cesium;

    //创建处理后的瓦片贴图，作为RTT的目标纹理
    var textureProcessed = new Texture({
      context: context,
      pixelFormat: PixelFormat.RGBA,
      pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
      sampler: sampler,
      width: texture.width,
      height: texture.height,
      flipY: texture.flipY,
      target: WebGLConstants.TEXTURE_2D,
      preMultiplyAlpha: params.preMultiplyAlpha,
    });
    var framebuffer = new Framebuffer({
      context: context,
      colorTextures: [textureProcessed],
      destroyAttachments: false,
    });
    const renderState = RenderState.fromCache({
      depthTest: {
        enabled: false,
      },
      blending: params.preMultiplyAlpha
        ? BlendingState.PRE_MULTIPLIED_ALPHA_BLEND
        : BlendingState.ALPHA_BLEND,
      viewport: {
        x: 0,
        y: 0,
        width: texture.width,
        height: texture.height,
      },
    });

    //传递原始瓦片贴图
    shaders.uniformMap.u_map = function () {
      return texture;
    };

    //画背景
    if (!Color.equals(params.bgColor, Color.TRANSPARENT)) {
      // console.log(context, "bgcommand");
      var bgCommand = context.createViewportQuadCommand(shaders.bgFS, {
        framebuffer: framebuffer,
        renderState: renderState,
        uniformMap: shaders.uniformMap,
      });
      bgCommand.execute(context);
    }

    // //瓦片加工
    var mainCommand = context.createViewportQuadCommand(shaders.mainFS, {
      framebuffer: framebuffer,
      renderState: renderState,
      uniformMap: shaders.uniformMap,
    });
    mainCommand.execute(context);
    framebuffer.destroy();
    texture.destroy();

    return textureProcessed;
  }
}

class Index extends React.Component {

  constructor(props) {
    super(props);
    console.log("参数");
    console.log(props);
    console.log(js);
    this.state =
    {
      drawOpen: true,
      modalOpen: false,
      streetName: "",
      projects: [
        {
          id: "1001",
          lonlat: [120.3025724675529, 30.414819264166333]
        },
        {
          id: "1002",
          lonlat: [120.3225724675529, 30.404819264166333]
        }
      ]
    }
  }

  zoom() {
    var width = document.body.clientWidth;
    var height = document.body.clientHeight;
    var maxWidth = 2400;
    var cx = width / maxWidth;
    console.log(cx);

    var maxHeight = 1200;
    var cy = height / maxHeight;
    console.log(cy);

    if (cx < cy)
      document.getElementById("box").style.zoom = cx;
    else
      document.getElementById("box").style.zoom = cy;
  }

  componentDidMount() {



    const _this = this;
    this.zoom();
    window.addEventListener('resize', this.zoom);
    var myChart = echarts.init(document.getElementById("cc"));
    myChart.setOption(
      {
        title: { text: '' },
        tooltip: {},
        xAxis: {
          data: ["6月", "7月", "8月"]
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [100, 120, 70]
        }]
      }
    );

    var myChart2 = echarts.init(document.getElementById("cc2"));
    myChart2.setOption(
      {
        title: { text: '' },
        tooltip: {},
        xAxis: {
          data: ["6月", "7月", "8月"]
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [100, 120, 70]
        }]
      }
    );

    var myChart3 = echarts.init(document.getElementById("cc3"));
    myChart3.setOption(
      {
        title: { text: '' },
        tooltip: {},
        xAxis: {
          data: ["6月", "7月", "8月", "6月", "7月", "8月"]
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [100, 120, 70, 11, 11, 11]
        }]
      }
    );


    var myChartb = echarts.init(document.getElementById("cb"));
    myChartb.setOption(
      {
        title: { text: '' },
        tooltip: {},
        xAxis: {
          data: ["6月", "7月", "8月", "6月", "7月", "8月"]
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [100, 120, 70, 100, 120, 70]
        }]
      }
    );

    var myChart2b = echarts.init(document.getElementById("cb2"));
    myChart2b.setOption(
      {
        title: { text: '' },
        tooltip: {},
        xAxis: {
          data: ["6月", "7月", "8月"]
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [100, 120, 70]
        }]
      }
    );



    //天地图
    // let [tiandiVecModel, tiandiImgModel] = getProviderViewModels();
    const viewer = new Cesium.Viewer("cesiumContainer", {
      contextOptions: {
        requestWebgl1: true,
      }
      // baseLayerPicker: false,//隐藏默认底图选择控件
      // imageryProviderViewModels: [tiandiVecModel, tiandiImgModel],
    })
    viewer.imageryLayers.get(0).show = false;
    viewer.scene.skyBox.show = false;
    viewer.scene.sun.show = false;
    viewer.scene.moon.show = false;
    viewer.scene.globe.baseColor = Cesium.Color.BLACK;
    viewer.scene.screenSpaceCameraController.tiltEventTypes = [];
    // viewer.scene.screenSpaceCameraController.enableRotate=false;

    function createTdtImageryProvider(params) {
      var tileMatrixSet = "w";
      var host = params.host || "http://t{s}.tianditu.com/";
      var subdomains = ["0", "1", "2", "3", "4", "5", "6", "7"];

      if (host[host.length - 1] == "/") {
        host = host.substr(0, host.length - 1);
      }

      var url =
        host +
        "/" +
        params.layer +
        "_" +
        tileMatrixSet +
        "/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=" +
        params.layer +
        "&tileMatrixSet=" +
        tileMatrixSet +
        "&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles";
      url += "&tk=" + params.appKey;

      let provider = new Cesium.WebMapTileServiceImageryProvider({
        url: url,
        layer: params.layer,
        style: "default",
        subdomains: subdomains,
        tileMatrixSetID: tileMatrixSet,
        maximumLevel: params.maximumLevel || 18,
        minimumLevel: params.minimumLevel,
      });

      return provider;
    }
    function createGovImageryProvider(params) {

      let accessKey = "BCDSGA_b3eb67db313179f6baa31fa9eabad28a";   //修改自己申请的accessKey，ak、sk不要弄反
      let secretKey = "BCDSGS_ff85da5929d640977e18e704795ab7f4";   //修改自己申请的secretKey，ak、sk不要弄反  

      //ak、sk和生成token建议在后端，避免前端调用的时候泄露
      let payload = JSON.stringify({
        "key": accessKey,
        "exp": new Date().setHours(new Date().getHours() + 1)
      });


      function base64UrlEncode(str) {
        var encodedSource = CryptoJS.enc.Base64.stringify(str);
        var reg = new RegExp('/', 'g');
        encodedSource = encodedSource.replace(/=+$/, '').replace(/\+/g, '-').replace(reg, '_');
        return encodedSource;
      }

      let header = JSON.stringify({
        "alg": "HS256",
        "typ": "JWT"
      })


      let secretSalt = "user";
      let before_sign = base64UrlEncode(CryptoJS.enc.Utf8.parse(header)) + '.' + base64UrlEncode(CryptoJS.enc.Utf8.parse(payload));
      let signature = CryptoJS.HmacSHA256(before_sign, secretKey);
      signature = base64UrlEncode(signature);
      let final_sign = before_sign + '.' + signature;
      console.log(final_sign)
      const baseUrl = params.url + '?jwt=' + final_sign + '&x-bg-auth-type=jwt_auth' // 网关地址
      // const baseUrl2 = url2+'?jwt='+final_sign+'&x-bg-auth-type=jwt_auth' // 网关地址


      let provider =
        new Cesium.WebMapTileServiceImageryProvider({
          url: baseUrl,
          layer: params.layer,
          style: "default",
          format: "image/png",
          tileMatrixSetID: 'EPSG:4326',
          tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
          tilingScheme: new Cesium.GeographicTilingScheme()
        });

      return provider;
    }
    //天地图
    // var imageryProvider = createTdtImageryProvider({
    //   layer: "vec",
    //   appKey: "7629c26d398f4c7bd23687e7ad6928ee",
    // });
    // var cvaProvider = createTdtImageryProvider({
    //   layer: "cva",
    //   appKey: "7629c26d398f4c7bd23687e7ad6928ee",
    // });
    //政务图
    //tdt_biaozhunyangshi_2017 标准样式
    //tdt_kejiganyangshi_2017  科技样式
    // const url1 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000009/mapserver/vmap/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017'	
    // const url2 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000011/mapserver/label/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017'
    // const url1 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220315000001/services/wmts/emap/default/oss'       //atg.biz.gettile  电子地图服务调用地址
    // const url2 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220323000008/services/wmts/emap_lab/default/oss'	  //atg.biz.gettile_lab 电子地图标注服务调用地址 
    // var imageryProvider = createGovImageryProvider({
    //   layer: "emap",
    //   url:"https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220315000001/services/wmts/emap/default/oss"
    // });
    // var cvaProvider = createGovImageryProvider({
    //   layer: "emap_lab",
    //   url:"https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220323000008/services/wmts/emap_lab/default/oss"
    // });
    var imageryProvider = createGovImageryProvider({
      layer: "emap",
      url: "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000009/mapserver/vmap/WMTS/1.0/zjvmap/tdt_biaozhunyangshi_2017"
    });
    // var cvaProvider = createGovImageryProvider({
    //   layer: "emap_lab",
    //   url:"https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000011/mapserver/label/WMTS/1.0/zjvmap/tdt_biaozhunyangshi_2017"
    // });
    // var imageryProvider = createGovImageryProvider({
    //   layer: "emap",
    //   url: "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000009/mapserver/vmap/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017"
    // });
    var cvaProvider = createGovImageryProvider({
      layer: "emap_lab",
      url: "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000011/mapserver/label/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017"
    });

    // //接下来我们就要对这个图层进行处理
    var layer = viewer.imageryLayers.addImageryProvider(imageryProvider);
    layer.alpha = 0.2;
    var layer2 = viewer.imageryLayers.addImageryProvider(cvaProvider);
    layer2.alpha = 0.8;
    //创建主题，设置相关参数
    const theme = new ImageryThemeGL({
      bgColor: Cesium.Color.BLACK,
      alpha: 0.9,
      invert: true,
      preMultiplyAlpha: true
    })
    //重写 layer._createTextureWebGL 方法
    var _createTextureWebGL = layer._createTextureWebGL;
    layer._createTextureWebGL = function (context, imagery) {
      var texture = _createTextureWebGL.bind(this)(context, imagery);
      var textureProcessed = theme.processTexture(context, texture);
      return textureProcessed || texture;
    };

    let yh = [120.2405724675529, 30.444819264166333];
    var scene = viewer.scene;
    // 将三维球定位到中国
    viewer.camera.setView({// fromDegrees()方法，将经纬度和高程转换为世界坐标
      destination: Cesium.Cartesian3.fromDegrees(yh[0], yh[1], 70000.0),
      orientation: {
        heading: 6.283185307179586,
        // 视角
        pitch: -1.5686521559334161,
        roll: 0,
      }
    })

    //加载gltf模型
    // var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
    // Cesium.Cartesian3.fromDegrees(120.3025724675529, 30.414819264166333, 0.0));
    // var model = scene.primitives.add(Cesium.Model.fromGltf({
    //   url: "../Apps/SampleData/models/CesiumGround/Cesium_Ground.gltf",
    //   modelMatrix: modelMatrix,
    //   minimumPixelSize: 512,
    //   maximumScale: 200000
    // }));


    // const jsonData = `https://geo.datav.aliyun.com/areas_v3/bound/440000_full.json`;
    const jsonData = `https://lpws.lanchensl.cn/lpdp/linping.geojson`;
    // jsonData一定要json文件

    const promise = Cesium.GeoJsonDataSource.load(jsonData
      ,
      {
        stroke: Cesium.Color.fromCssColorString("#bce672"),
        fill: Cesium.Color.fromCssColorString("#425066").withAlpha(0.8),
        strokeWidth: 3,
        markerSize: 10,
        markerSymbol: "?",
      }
    );
    promise.then(function (dataSource) {

      // viewer.dataSources.add(dataSource);

      var entities = dataSource.entities.values;
      var colorHash = {};
      for (var o = 0; o < entities.length; o++) {
        var r = entities[o];
        // if (r.name == "临平街道") {
        console.log(r, 110);


        //获取坐标
        let positions = r.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
        let polyCenter = Cesium.BoundingSphere.fromPoints(positions).center;
        polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
        let grpc = Cesium.Cartographic.fromCartesian(polyCenter, viewer.scene.globe.ellipsoid, new Cesium.Cartographic());
        let lng = Cesium.Math.toDegrees(grpc.longitude);
        let lat = Cesium.Math.toDegrees(grpc.latitude);

        //创建边缘线
        const polylines = scene.primitives.add(
          new Cesium.PolylineCollection()
        );
        // const polyline = polylines.add({
        //   positions: positions,
        //   width: 5.0,
        //   show: true,
        // });
        // polylines.customShader=customShader;
        const material =
          new Cesium.Material({
            fabric: {
              type: 'PolylinePulseLink',
              uniforms: {
                color: new Cesium.Color.fromCssColorString('#306090'),
                image: '/cabe.png',
                speed: 1,
              },
              source: 'czm_material czm_getMaterial(czm_materialInput materialInput)\n\
              {\n\
                  czm_material material = czm_getDefaultMaterial(materialInput);\n\
                  vec2 st = materialInput.st;\n\
                  vec4 colorImage = texture2D(image, vec2(fract((st.t - speed*czm_frameNumber*0.005)), st.t));\n\
                  vec4 fragColor;\n\
                  fragColor.rgb = color.rgb / 1.0;\n\
                  fragColor = czm_gammaCorrect(fragColor);\n\
                  material.alpha = colorImage.a * color.a;\n\
                  material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
                  material.emission = fragColor.rgb;\n\
                  return material;\n\
              }',
            },
            translucent: function () {
              return true
            },
          });
        // polyline.material = material2;
        // polyline.material= Cesium.Material.fromType(Cesium.Material.PolylineGlowType, {
        //   color: Cesium.Color.fromCssColorString("#93b3e2").withAlpha(0.7),
        //   glowPower: 0.1,
        //   // taperPower:0.1,
        // });

        // polyline.material= Cesium.Material.fromType(Cesium.Material.PolylineOutlineType, {
        //   color: Cesium.Color.BLUE.withAlpha(0.7),
        //   outlineColor:Cesium.Color.GREEN.withAlpha(0.7),
        //   outlineWidth:5
        // });

        // }
        // const polyline2 = polylines.add({
        //   positions: positions,
        //   width: 6.0,
        //   show: true,
        //   arcType: Cesium.ArcType.RHUMB
        // });
        // polyline2.material=  Cesium.Material.fromType(Cesium.Material.PolylineArrowType, {
        //   color: Cesium.Color.fromCssColorString("#00BFFF").withAlpha(1)
        // });
        r.nameID = o;   //给每条线添加一个编号，方便之后对线修改样式

        //添加街道
        //           var customShader = new Cesium.CustomShader({
        //     lightingModel: Cesium.LightingModel.UNLIT,
        //     fragmentShaderText: `
        //         void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
        //             float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
        //             float _heightRange = 60.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
        //             float _glowRange = 300.0; // 光环的移动范围(高度)
        //             float vtxf_height = fsInput.attributes.positionMC.z-_baseHeight;
        //             float vtxf_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
        //             float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.1;
        //             material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);
        //             float vtxf_a13 = fract(czm_frameNumber / 360.0);
        //             float vtxf_h = clamp(vtxf_height / _glowRange, 0.0, 1.0);
        //             vtxf_a13 = abs(vtxf_a13 - 0.5) * 2.0;
        //             float vtxf_diff = step(0.005, abs(vtxf_h - vtxf_a13));
        //             material.diffuse += material.diffuse * (1.0 - vtxf_diff);
        //         }       
        //         `,
        // });
        const polygon = viewer.entities.add({
          name: "n_" + r.name,
          polygon:
          {
            hierarchy: {
              positions: positions
            },
            extrudedHeight: 0,
            // material: new Cesium.ColorMaterialProperty(Cesium.Color.fromCssColorString("#253d5f").withAlpha(0.2)),
            arcType: Cesium.ArcType.RHUMB,
            height: 200,
            // outline: true,
            // outlineColor: Cesium.Color.fromCssColorString("#93b3e2"),
            // outlineWidth: 0
          }
        });
        polygon.polygon.material = new Cesium.ImageMaterialProperty({
          transparent: true,//设置透明
          color: new Cesium.Color.fromCssColorString("#ffffff").withAlpha(0.1),
          image: "/tl.png",
          repeat: new Cesium.Cartesian2(1, 2),
        });


        function DynamicWallMaterialProperty(options) {
          this._definitionChanged = new Cesium.Event();
          this._color = undefined;
          this._colorSubscription = undefined;
          this.color = options.color || Color.BLUE;
          this.duration = options.duration || 1000;
          this.trailImage = options.trailImage;
          this._time = (new Date()).getTime();
        }

        /**
    * 带方向的墙体
    * @param {*} options.get:true/false
    * @param {*} options.count:数量 
    * @param {*} options.freely:vertical/standard
    * @param {*} options.direction:+/-
    */
        function _getDirectionWallShader(options) {
          if (options && options.get) {
            var materail = "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
        {\n\
            czm_material material = czm_getDefaultMaterial(materialInput);\n\
            vec2 st = materialInput.st;";
            if (options.freely == "vertical") { //（由下到上）
              materail += "vec4 colorImage = texture2D(image, vec2(fract(st.s), fract(float(" + options.count + ")*st.t" + options.direction + " time)));\n\ ";
            } else { //（逆时针）
              materail += "vec4 colorImage = texture2D(image, vec2(fract(float(" + options.count + ")*st.s " + options.direction + " time), fract(st.t)));\n\ ";
            }
            //泛光
            materail += "vec4 fragColor;\n\
            fragColor.rgb = (colorImage.rgb+color.rgb) / 1.0;\n\
            fragColor = czm_gammaCorrect(fragColor);\n\
            material.diffuse = colorImage.rgb;\n\
            material.alpha = colorImage.a;\n\
            material.emission = fragColor.rgb;\n\
            return material;\n\
        }";
            return materail
          }
        } Object.defineProperties(DynamicWallMaterialProperty.prototype, {
          isConstant: {
            get: function () {
              return false;
            }
          },
          definitionChanged: {
            get: function () {
              return this._definitionChanged;
            }
          },
          color: Cesium.createPropertyDescriptor('color')
        });

        var MaterialType = 'wallType' + parseInt(Math.random() * 1000);
        DynamicWallMaterialProperty.prototype.getType = function (time) {
          return MaterialType;
        };

        DynamicWallMaterialProperty.prototype.getValue = function (time, result) {
          if (!Cesium.defined(result)) {
            result = {};
          }
          result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
          result.image = this.trailImage;
          if (this.duration) {
            result.time = (((new Date()).getTime() - this._time) % this.duration) / this.duration;
          }
          viewer.scene.requestRender();
          return result;
        };

        DynamicWallMaterialProperty.prototype.equals = function (other) {
          return this === other ||
            (other instanceof DynamicWallMaterialProperty
              && Cesium.Property.equals(this._color, other._color))
        };

        Cesium.Material._materialCache.addMaterial(MaterialType, {
          fabric: {
            type: MaterialType,
            uniforms: {
              color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
              image: Cesium.Material.DefaultImageId,
              time: -20
            },
            source: _getDirectionWallShader({
              get: true,
              count: 3.0,
              freely: 'vertical',
              direction: '-'
            })
          },
          translucent: function (material) {
            return true;
          }
        });

        viewer.entities.add({
          wall: {
            positions: positions,
            maximumHeights: new Array(positions.length).fill(500),
            minimunHeights: new Array(positions.length).fill(500),
            //  material: new Cesium.ImageMaterialProperty({
            //   transparent: true,//设置透明
            //   image: "/bb.png",
            //   repeat: new Cesium.Cartesian2(10, -10),
            // }),
            material: new DynamicWallMaterialProperty({ trailImage: '/tl.png', color: Cesium.Color.BLUE.withAlpha(0.7), duration: 1500 })
          },
        });


        //添加中心区域
        // viewer.entities.add({
        //   id: "l_" + o,
        //   name: r.name,
        //   position: Cesium.Cartesian3.fromDegrees(lng, lat),
        //   // 文字
        //   label: {
        //     eyeOffset: new Cesium.Cartesian3(0, 0, -1000),
        //     // 文本。支持显式换行符“ \ n”
        //     text: r.name + " 100个",
        //     // 字体样式，以CSS语法指定字体
        //     font: '20pt 微软雅黑',
        //     // 字体颜色
        //     fillColor: Cesium.Color.WHITE,
        //     // 背景颜色
        //     backgroundColor: Cesium.Color.fromCssColorString("#1189e1").withAlpha(0.9),
        //     // 是否显示背景颜色
        //     showBackground: true,
        //     // 字体边框
        //     outline: true,
        //     // 字体边框颜色
        //     outlineColor: Cesium.Color.WHITE,
        //     // 字体边框尺寸
        //     outlineWidth: 10,
        //     // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
        //     scale: 0.5,
        //     // 设置样式：FILL：填写标签的文本，但不要勾勒轮廓；OUTLINE：概述标签的文本，但不要填写；FILL_AND_OUTLINE：填写并概述标签文本。
        //     style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        //     // 相对于坐标的水平位置
        //     verticalOrigin: Cesium.VerticalOrigin.CENTER,
        //     // 相对于坐标的水平位置
        //     horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        //     // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
        //     pixelOffset: new Cesium.Cartesian2(10, 0),
        //     // 显示在距相机的距离处的属性，多少区间内是可以显示的
        //     distanceDisplayCondition: new Cesium.DistanceDisplayCondition(30000, 80000),
        //     // 是否显示
        //     show: true
        //   }
        // });
      }


      // //添加余杭
      // viewer.entities.add({
      //   id: "vl_yh",
      //   position: Cesium.Cartesian3.fromDegrees(yh[0], yh[1]),
      //   // 文字
      //   label: {
      //     eyeOffset: new Cesium.Cartesian3(0, 0, -1000),
      //     // 文本。支持显式换行符“ \ n”
      //     text: "临平区 599个",
      //     // 字体样式，以CSS语法指定字体
      //     font: '10pt 微软雅黑',
      //     // 字体颜色
      //     fillColor: Cesium.Color.WHITE,
      //     // 背景颜色
      //     backgroundColor: Cesium.Color.fromCssColorString("#8911e1").withAlpha(0.9),
      //     // 是否显示背景颜色
      //     showBackground: true,
      //     // 字体边框
      //     outline: true,
      //     // 字体边框颜色
      //     outlineColor: Cesium.Color.WHITE,
      //     // 字体边框尺寸
      //     outlineWidth: 10,
      //     // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
      //     scale: 1.0,
      //     // 设置样式：FILL：填写标签的文本，但不要勾勒轮廓；OUTLINE：概述标签的文本，但不要填写；FILL_AND_OUTLINE：填写并概述标签文本。
      //     style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      //     // 相对于坐标的水平位置
      //     verticalOrigin: Cesium.VerticalOrigin.CENTER,
      //     // 相对于坐标的水平位置
      //     horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      //     // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
      //     pixelOffset: new Cesium.Cartesian2(10, 0),
      //     // 显示在距相机的距离处的属性，多少区间内是可以显示的
      //     distanceDisplayCondition: new Cesium.DistanceDisplayCondition(30000, 200000),
      //     // 是否显示
      //     show: true
      //   }
      // });



      var temp = new Array();
      window.Hightlightline = function (nameid) {
        // var exists = temp.indexOf(nameid);
        // if (exists <= -1) {
        //   Highlight(nameid, 50, 50);
        //   temp.push(nameid);  // 添加线nameID到数组，
        // }
        // else  //已经是高亮状态了 再次点击修改为原始状态
        // {
        //   Highlight(nameid, 10, 10);
        //   temp.splice(exists, 1);  //删除对应的nameID
        // }
      }
      var om = null;
      window.Highlight = function (nameid, width1, width2) {
        // for (var o = 0; o < entities.length; o++) {
        //   var m = entities[o];
        //   if (om == null) om = m.polygon.material;
        //   if (nameid == o) {
        //     console.log("变换样式!");
        //     console.log(m);
        //     m.polygon.material = new Cesium.PolylineGlowMaterialProperty({
        //       glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
        //       color: Cesium.Color.ORANGERED.withAlpha(.9)
        //     })
        //   } else {
        //     m.polygon.material = om;
        //   }
        // }
      }

    });
    // viewer.flyTo(promise);
    //-------------------------------------------------------------------------

    viewer.scene.light = new Cesium.DirectionalLight({
      direction: Cesium.Cartesian3.fromDegrees(yh[0], yh[1])
    })

    const entities = viewer.entities; //将enities方法保存到变量中创建广告牌
    this.state.projects.map((o) => {
      entities.add({
        id: "p_" + o.id,
        position: Cesium.Cartesian3.fromDegrees(o.lonlat[0], o.lonlat[1]),
        show: true,
        billboard: {
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM, //对齐方式
          pixelOffset: new Cesium.Cartesian2(10), //图片的上下左右偏移,正为右，下
          sizeInMeters: false, //随着缩放而缩放
          width: 20,
          height: 40,
          image: "/pos.png", //广告牌内容
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 30000),
        },
      });
    });

    //  let startPosition = new Cesium.Cartesian3.fromDegrees(120.3025724675529,30.414819264166333);
    //  let endPosition = new Cesium.Cartesian3.fromDegrees(120.3225724675529, 30.404819264166333);
    //  let factor = 0;
    // 添加模型
    //  entities.add({
    //     id: "test3",
    //      position: Cesium.Cartesian3.fromDegrees(120.3236724675529, 30.404819264166333),
    //     // position: new Cesium.CallbackProperty(function() {
    //     //    if (factor < 100) {
    //     //       factor++;
    //     //    }
    //     //    // 动态更新位置
    //     //    return Cesium.Cartesian3.lerp(startPosition, endPosition, factor / 100.0, new Cesium.Cartesian3());
    //     // }, true),
    //     billboard: {
    //       verticalOrigin: Cesium.VerticalOrigin.BOTTOM, //对齐方式
    //       pixelOffset: new Cesium.Cartesian2(10), //图片的上下左右偏移,正为右，下
    //       sizeInMeters: false, //随着缩放而缩放
    //       width: 20,
    //       height: 40,
    //       image: "/pos.png", //广告牌内容
    //     },
    //  });

    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {//判断是否支持图像渲染像素化处理
      viewer.resolutionScale = window.devicePixelRatio;
    }
    //是否开启抗锯齿
    viewer.scene.fxaa = true;
    viewer.scene.postProcessStages.fxaa.enabled = true;
    // console.log(viewer);

    viewer.camera.changed.addEventListener(() => {
      let height = viewer.camera.positionCartographic.height;
      console.log("当前高度:", height);
      // for (var i = 0; i < entities.values.length; i++) {
      //   if (entities.values[i].id.indexOf("p_") != -1 && height > 30000) {
      //     entities.values[i].show = false;
      //   }
      //   if (entities.values[i].id.indexOf("p_") != -1 && height <= 30000) {
      //     entities.values[i].show = true;
      //   }
      //   if (entities.values[i].id.indexOf("l_") != -1 && height > 30000) {
      //     entities.values[i].show = true;
      //   }
      //   if (entities.values[i].id.indexOf("l_") != -1 && height <= 30000) {
      //     entities.values[i].show = false;
      //   }
      // }
    });
    viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
      var pickedFeature = viewer.scene.pick(movement.position);
      _this.setState({ streetName: "" });
      if (typeof (pickedFeature) != "undefined")   //鼠标是否点到线上
      {
        console.log("点击", pickedFeature);
        if (pickedFeature.id != undefined) {
          var name = pickedFeature.id.name;
          console.log("点击", name);
          _this.setState({ streetName: name, modalOpen: true });
          var name_id = pickedFeature.id.nameID;  //获取每条线的nameID
          // Hightlightline(name_id);
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );
    viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
      let pickedFeatureStart = viewer.scene.pick(movement.startPosition);
      let pickedFeatureEnd = viewer.scene.pick(movement.endPosition);
      // console.log('鼠标滑动结束位置实体对象',pickedFeatureEnd)
      // console.log('鼠标滑动开始位置实体对象',pickedFeatureStart)
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  }


  render() {

    const { Drawer, Modal } = antd;
    const onClose = () => {

    };
    const dStyle = {
      backgroundColor: 'transparent',
      boxShadow: '0px 0px 20px #d0d0d0'
    };


    const topD = [
      {
        label: '在建项目(个)',
        value: 231356,
        color: '#75D7FD'
      },
      {
        label: '高风险项目(个)',
        value: 1,
        color: '#FF577B'
      },
      {
        label: '危大工程项目数(个)',
        value: 231356,
        color: '#F0A04B'
      },
      {
        label: '危大工程数(个)',
        value: 231356,
        color: '#F0A04B'
      },
      {
        label: '超危大工程项目数(项)',
        value: 231356,
        color: '#FF577B'
      },
      {
        label: '超危大工程数(项)',
        value: 231356,
        color: '#FF577B'
      }
    ];


    return (
      <div>
        <Modal closeIcon={false} open={this.state.modalOpen} footer={null} maskClosable={true} onCancel={() => { this.setState({ modalOpen: false }); }}>
          {this.state.streetName}
        </Modal>

        <div id="box">
          <div class="top"><img src="http://localhost:8080/images/top-title1.png" alt="" class="title-bg" />
            <div class="title"><p>临平区建设工地数智风控平台</p><p>工地平安临距离</p></div></div>
          <div class="left">
            <div class="card-container">
              <div class="header">
                <div class="title"><span>人员信息</span></div>
                <div class="title__right f">
                  <span>统计数据截止：2023年9月20日24时</span>&nbsp;<span class="ml-4">详情</span></div>
              </div>
              <div class="body">
                <div class="item-container flex flex-col p-3">
                  <div class="top flex justify-center items-center flex-1 flex-colum">
                    <div class="flex">
                      <div class="flex mr-9">
                        <div class="icon">
                          <img src="http://localhost:8080/images/zaizhi.png" class="img1" />
                        </div>
                        <div class="ml-3">
                          <span>在职人员(人)</span>
                          <span>14789</span>
                        </div>
                      </div>
                      <div class="flex mr-9">
                        <div class="icon">
                          <img src="http://localhost:8080/images/jinrichuqin.png" class="img1" />
                        </div>
                        <div class="ml-3">
                          <span>今日出勤(人)</span>
                          <span>1000</span>
                        </div>
                      </div>
                      <div class="flex">
                        <div class="icon">
                          <img src="http://localhost:8080/images/jinrijinchang.png" class="img1" />
                        </div>
                        <div class="ml-3">
                          <span>今日进场(人)</span>
                          <span>432</span>
                        </div>
                      </div>
                    </div>
                    <div class="flex mt-4">
                      <div class="flex mr-9">
                        <div class="icon">
                          <img src="http://localhost:8080/images/normal-person.png" class="img2" />
                        </div>
                        <div class="ml-3">
                          <span class="title_s">普通人员(人)</span>
                          <span>12569</span>
                        </div>
                      </div>
                      <div class="flex mr-9">
                        <div class="icon">
                          <img src="http://localhost:8080/images/manage-person.png" class="img2" />
                        </div>
                        <div class="ml-3">
                          <span class="title_s">管理人员(人)</span>
                          <span>23</span>
                        </div>
                      </div>
                      <div class="flex">
                        <div class="icon">
                          <img src="http://localhost:8080/images/special-person.png" class="img2" />
                        </div>
                        <div class="ml-3">
                          <span class="title_s">特殊工种(人)</span>
                          <span>134</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="bottom">
                    <div class="title">近30日项目平均考勤率</div>
                    <div class="percentage relative">
                      <div class="bg absolute" />
                      <div class="num absolute" />
                    </div>
                    <span>60%</span>
                    <div class="title mt-9">近30日管理人员平均考勤率</div>
                    <div class="percentage relative">
                      <div class="bg absolute" />
                      <div class="num absolute" />
                    </div>
                    <span>60%</span>
                  </div>
                </div>

              </div>
            </div>
            <div class="card-container">
              <div class="header">
                <div class="title"><span>人员信息</span></div>
                <div class="title__right f">
                  <span>统计数据截止：2023年9月20日24时</span>&nbsp;<span class="ml-4">详情</span></div>
              </div>
              <div class="body">
                <div class="item-container flex flex-col p-3">
                  <div class="top flex">
                    <div id="cc" style={{ width: '78px', height: '78px' }}></div>
                    <div class="value">
                      关键岗位考勤率
                      <p style={{ fontSize: '24px', fontWeight: '500', color: '#fff' }}>44%</p>
                    </div>
                    <div class="divider" />
                    <div id="cc2" style={{ width: '78px', height: '78px' }}></div>
                    <div class="value">
                      特殊工种考勤率
                      <p style={{ fontSize: '24px', fontWeight: '500', color: '#fff' }}>44%</p>
                    </div>
                  </div>
                  <div id="cc3" style={{ width: '100%', height: '300px' }}></div>
                </div>
              </div>
            </div>
            <div class="card-container">
              <div class="header">
                <div class="title"><span>物联网设备</span></div>
                <div class="title__right f">
                  <span class="ml-4">详情</span></div>
              </div>
              <div class="body">
                <div class="item-container flex justify-around p-3">
                  <div class="item flex flex-col items-center">
                    <div class="title">扬尘监测</div>
                    <img src="http://localhost:8080/images/yangchen.png" />
                    <div class="num text-[#FF577B]">2378</div>
                    <div>告警项目数</div>
                  </div>
                  <div class="item flex flex-col items-center">
                    <div class="title">起重机械</div>
                    <img src="http://localhost:8080/images/qizhong.png" />
                    <div class="num">2378</div>
                    <div>已安装设备项目数</div>
                  </div>
                  <div class="item flex flex-col items-center">
                    <div class="title">深基坑</div>
                    <img src="http://localhost:8080/images/shenjikeng.png" />
                    <div class="num">2378</div>
                    <div>深基坑项目数</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right">
            <div class="card-container">
              <div class="header">
                <div class="title"><span>AI预警</span></div>
                <div class="title__right f">
                  <span class="ml-4">详情</span></div>
              </div>
              <div class="body">
                <div class="item-container flex justify-around p-3">
                  <div id="cb" style={{ width: '100%', height: '300px' }}></div>
                </div>
              </div>
            </div>
            <div class="card-container">
              <div class="header">
                <div class="title"><span>综合监管</span></div>
                <div class="title__right f">
                  <span class="ml-4">详情</span></div>
              </div>
              <div class="body">
                <div class="item-container flex flex-col p-3">
                  <div class="top flex justify-center items-center">
                    <div class="flex">
                      <div class="top_item flex justify-between items-center">
                        {/* <iconpark-icon name="weichuli" class="icon" /> */}
                        <div>
                          <span>未处理数(个)</span>
                          <span>6</span>
                        </div>
                      </div>
                      <div class="top_item flex justify-between items-center">
                        {/* <iconpark-icon name="yichuli" class="icon" /> */}
                        <div>
                          <span>已处理数(个)</span>
                          <span>6</span>
                        </div>
                      </div>
                      <div class="top_item flex justify-between items-center">
                        {/* <iconpark-icon name="fa" class="icon" /> */}
                        <div>
                          <span>处罚次数(个)</span>
                          <span>6</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div id="cb2" style={{ width: '100%', height: '200px' }}></div>
                  <div class="bottom flex justify-center items-center text-center">
                    <div class="percentage size-12">
                      {/* <commonChart ref="problemsChartRef" /> */}
                      <span>一级风险 100个 占比25%</span>
                      <span>二级风险 100个 占比25%</span>
                      <span>三级风险 100个 占比25%</span>
                      <span>四级风险 100个 占比25%</span>
                    </div>
                    <div class="percentage size-12">
                      {/* <commonChart ref="punishChartRef" /> */}
                      <span>简易处罚 100条</span>
                      <span>责令提供 100条</span>
                      <span>行政处罚 100条</span>
                      <span>信用惩戒 100条</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="card-container">
              <div class="header">
                <div class="title"><span>工地驿站</span></div>
                <div class="title__right f">
                  <span class="ml-4">详情</span></div>
              </div>
              <div class="body">
                <div class="item-container" style={{ height: '200px' }}>
                  <div class="flex flex-wrap absolute" style={{ scale: 0.9 }}>
                    <div class="pl-2 mb-2 mr-4 bg">
                      <img src="http://localhost:8080/images/event-icon1.png" class="icon" />
                      <div class="flex-1">
                        <p class="text-base text-2c">节约总时间</p>
                        <p class="text-2xl font-bold leading-7 text-3c">142<span class="text-xs">小时</span></p>
                      </div>
                    </div>
                    <div class="mb-2 bg">
                      <div class="bg" style={{ paddingLeft: '40px' }}>
                        <img src="http://localhost:8080/images/event-icon2.png" class="icon" />
                        <div class="flex-1">
                          <p class="text-base text-2c">今日处理事件</p>
                          <p class="text-2xl font-bold leading-7 text-3c">1<span class="text-xs">件</span></p>
                        </div>
                      </div>
                    </div>

                    <div class="pl-2 mr-4 bg">
                      <img src="http://localhost:8080/images/event-icon3.png" class="icon" />
                      <div class="flex-1">
                        <p class="text-base text-2c">压缩时间比</p>
                        <p class="text-2xl font-bold leading-7 text-3c">6<span class="text-xs">%</span></p>
                      </div>
                    </div>
                    <div class="bg">
                      <div class="bg" style={{ paddingLeft: '40px' }}>
                        <img src="http://localhost:8080/images/event-icon3.png" class="icon" />
                        <div class="flex-1">
                          <p class="text-base text-2c">今日压缩时间比</p>
                          <p class="text-2xl font-bold leading-7 text-3c">35<span class="text-xs">小时</span></p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="flex w-[520px] justify-center text-center">
                    <div class="bg2">
                      <div class="flex-1">
                        <p class="text-base text-white text-2c">总处理事件</p>
                        <p class="mt-1 text-4xl font-bold text-3c">100<span class="text-xs">件</span></p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="center flex flex-col">
            <div class="screen-overview">
              <div class="screen-overview_box flex justify-between items-center">
                {
                  topD.map((item, index) => {
                    return (<div class="screen-overview_item flex flex-col justify-center items-center">
                      <span class="text" style={{ color: item.color }}>{item.value}</span>
                      <span class="label">{item.label}</span>
                    </div>);
                  })
                }
              </div>
            </div>
          </div>
        </div>
        {/* <div style={{ left: '0px', top: '0px', width: '360px', height: '100%', position: 'fixed', zIndex: 10000 }}>
          <div id="cc" style={{ width: '100%', height: '300px' }}></div>
          <div id="cc2" style={{ width: '100%', height: '300px' }}></div>
          <div id="cc3" style={{ width: '100%', height: '300px' }}></div>
        </div>

        <div style={{ right: '0px', top: '0px', width: '360px', height: '100%', position: 'fixed', zIndex: 10000 }}>
          <div id="cb" style={{ width: '100%', height: '300px' }}></div>
          <div id="cb2" style={{ width: '100%', height: '300px' }}></div>
          <div id="cb3" style={{ width: '100%', height: '300px' }}></div>
        </div> */}

        {/* <Drawer placement="left" open={this.state.drawOpen} style={dStyle} closable={false} mask={false} width={360}>

        </Drawer>

        <Drawer placement="right" open={this.state.drawOpen} style={dStyle} closable={false} mask={false} width={360}>

        </Drawer> */}

        <div id="cesiumContainer" style={{ position: 'absolute', left: '0px', top: '0px', margin: '0', padding: '0', width: '100%', height: '100%' }} />
      </div>
    );
  }
}
export default withRouter(Index);